<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax文件分块上传</title>
</head>
<body>
<p>在 demo2.html 的基础上增加一次上传成功的回调方法。</p>
<form action="upload.php">
<input type="file" id="file">
</form>
<script src="jquery-1.11.0.js"></script>
<script>
~function($){
// 每次上传文件的一段，单位：字节
var preUploadSize = 1024 * 2

var start = 0
var xhr = new XMLHttpRequest()
var total = 0
xhr.upload.onprogress = function(e) {
	total += e.loaded
	document.title = '上传 ' + total + ' 字节'
}

$('#file').change(function() {
	var files = this.files
	var file = files[0]
	upload(file)
})

function upload(file) {
	var data = new FormData()
	data.append("name", encodeURIComponent(file.name))
	data.append("file", file.slice(start, start + preUploadSize))
	
	xhr.open("post", 'upload.php')
	
	// 在 demo2.html 的基础上增加一次上传成功的回调方法
	xhr.onreadystatechange = function(e) {
		var json
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				try {
					json = JSON.parse(xhr.responseText)
					if (json && json.succ) {
						alert('一次上传结束')
					}
				} catch (e) {
					alert('上传错误')
				}
			} else {
				alert('上传错误')
			}
		}
	}
	
	xhr.send(data)
}
}(jQuery)
</script>
</body>
</html>